/*******************************************************************************
 * Copyright (c) 2006 CEA List.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     CEA List - initial API and implementation
 *******************************************************************************/
package com.cea.papyrus.core.commands.connection;

import org.eclipse.draw2d.geometry.Point;

import com.cea.papyrus.diagraminterchange2.di2.GraphEdge;

/**
 * Command that create bendpoint.
 * 
 * @author Patrick Tessier
 */
public class CreateBendpointCommand extends BendpointCommandBase {
	  
  	/**
  	 * 
  	 */
  	private GraphEdge connection;
	  
  	/**
  	 * 
  	 */
  	private Point location; 
	  
  	/**
  	 * 
  	 */
  	private int index; 
	  
	  /**
  	 * 
  	 */
  	private SegmentAnchors seg1;
	  
  	/**
  	 * 
  	 */
  	private SegmentAnchors seg2;

	  
	  /**
  	 * 
  	 * 
  	 * @return 
  	 */
  	public boolean canExecute()
	  {
		  return true;
	  }
	  
	  /**
  	 * 
  	 */
  	@Override
	public void execute() {
		  // save anchors of old segments (index-1)
		  Point src = getSegmentSourceLocation(connection, index);
		  Point target = getSegmentTargetLocation(connection, index);
		  Point middle = middlePoint(src, target);
		  // create two saved segments using the midpoint as separator
		  seg1 = new SegmentAnchors( src, middle, connection.getAnchorage());
		  seg2 = new SegmentAnchors( middle, target, connection.getAnchorage());
		  // move both segments
		  seg1.moveTargetEnd(location);
		  seg2.moveSourceEnd(location);
		  
		  // add the point to model
	    connection.getWaypoints().add(index, location);// addBendpoint in the GraphEdge
	  }

	  /**
  	 * Redo the command.
  	 */
	  public void redo()
	  {
		  // move both segments
		  seg1.moveTargetEnd(location);
		  seg2.moveSourceEnd(location);
		  
		  // add the point to model
	    connection.getWaypoints().add(index, location);// addBendpoint in the GraphEdge
	  }
	  
	  
	  /**
  	 * 
  	 * 
  	 * @param model 
  	 */
  	public void setConnection(Object model) {
	    connection = (GraphEdge) model;
	  }

	  /**
  	 * 
  	 * 
  	 * @param i 
  	 */
  	public void setIndex(int i) {
	   
	    index = i;
	  }

	  /**
  	 * 
  	 * 
  	 * @param point 
  	 */
  	public void setLocation(Point point) {
	    location = point;
	  }

	  
	  /**
  	 * 
  	 */
  	@Override
	public void undo() {
	    connection.getWaypoints().remove(index);
	    seg1.restoreAnchors();
	    seg2.restoreAnchors();
	  }
	  
	}
